package com.tanhua.admin.listtener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tanhua.admin.service.LogService;
import com.tanhua.model.db.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class LogListener {

    @Autowired
    private LogService logService;

    @RabbitListener(
            // 绑定, 绑定交换与队列，通过key来绑定。消息发送给交换机，如果消费中的routingkey匹配bindingKey,就会把消息转经这个绑定的队列
            bindings = @QueueBinding(
                    value = @Queue("tanhua.log.queue"),
                    exchange = @Exchange(name = "tanhua.log.exchange", type = ExchangeTypes.TOPIC),
                    key = "log.*"
            )
    )
    public void logMsg(String msg){
        log.info("日志消费者：" + msg);
        //1. 解析消息内容为map
        JSONObject jsonObject = JSON.parseObject(msg);
        //2. 构建log pojo
        Log pojo = new Log();
        pojo.setUserId(jsonObject.getLong("userId"));
        pojo.setType(jsonObject.getString("type"));
        pojo.setLogTime(jsonObject.getString("logTime"));
        pojo.setPlace("中粮黑马");
        pojo.setEquipment("iphone 13");
        pojo.setCreated(new Date());
        //3. 调用service添加log记录
        logService.add(pojo);
        log.info("完成 日志消费者：" + msg);
    }
}
